<template>
  <div id="register">
    <LoginTop title="登录嗨皮happy">
      <div
        slot="right"
        class="slot"
        @click="
          () => {
            this.$router.push('/register');
          }
        "
      >
        切换到注册
      </div>
    </LoginTop>
    <LoginInput
      class="username"
      label="账号"
      placeholder="请输入账号"
      rule="^.{6,13}$"
      @sucessInput="sucessUserName"
    />
    <LoginInput
      label="密码"
      type="password"
      placeholder="请输入密码"
      rule="^.{6,13}$"
      @sucessInput="sucessPassword"
    />
    <LoginButton text="登录" @submitClick="loginClick" />
  </div>
</template>

<script>
import LoginTop from "@/components/common/LoginTop.vue";
import LoginInput from "@/components/common/LoginInput.vue";
import LoginButton from "@/components/common/LoginButton.vue";

export default {
  components: {
    LoginTop,
    LoginInput,
    LoginButton,
  },
  data() {
    return {
      userinfo: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    sucessUserName(res) {
      this.userinfo.username = res;
    },
    sucessPassword(res) {
      this.userinfo.password = res;
    },
    loginClick() {
      if (!this.userinfo.username) {
        this.$toast.fail("用户名不存在");
      } else if (!this.userinfo.password) {
        this.$toast.fail("密码错误");
      } else {
        this.submit();
      }
    },
    async submit() {
      let res = await this.$http.post("/login", this.userinfo);
      let data = res.data;
      this.$toast.fail(data.msg);
      if (data.code === 200) {
        /* 登录成功 内存保留用户数据 */
        localStorage.setItem("id", data.id);
        localStorage.setItem("token", data.token);
        /* 1s后跳转个人中心 */
        setTimeout(() => {
          this.$router.replace("/userinfo");
        }, 1000);
      }
    },
  },
};
</script>

<style lang="less" scoped>
#register {
  .username {
    margin: 4.167vw 0;
  }
  .slot {
    font-size: 3.611vw;
    color: rgb(97, 96, 96);
  }
}
</style>
